package com.saas.ability.gateway.filter;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.saas.ability.core.base.protocol.BaseOutput;
import com.saas.ability.gateway.base.protocol.input.ReqHeaderInput;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

public abstract class AbstractFilter extends ZuulFilter{
	
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	protected String HEADER = "req-header";
	
	protected String VERIFY_VERSION = "verify-version";
	protected String VERIFY_TOKEN = "verify-token";
	
	private final static String APP_VERSION = "appVersion";
	private final static String API_VERSION = "apiVersion";
	private final static String DEVICE_VERSION = "deviceVersion";
	private final static String DEVICE_SN = "deviceSn";
	private final static String DEVICE_TYPE = "deviceType";
	private final static String TERMINAL_TYPE = "terminalType";
	private final static String FROM_TYPE = "fromType";
	private final static String TIMESTAMP = "timestamp";
	private final static String ACCESS_TOKEN = "accessToken";
	private final static String SIGNATURE = "signature";
		
	public ReqHeaderInput parseReqHeader(RequestContext ctx){
		HttpServletRequest request = ctx.getRequest();
		ReqHeaderInput reqHeaderInput = new ReqHeaderInput();
		reqHeaderInput.setAppVersion(request.getHeader(APP_VERSION));
		reqHeaderInput.setApiVersion(request.getHeader(API_VERSION));
		reqHeaderInput.setDeviceVersion(request.getHeader(DEVICE_VERSION));
		reqHeaderInput.setDeviceSn(request.getHeader(DEVICE_SN));
		
		String deviceType = request.getHeader(DEVICE_TYPE);
		if(!StringUtils.isEmpty(deviceType)){
			reqHeaderInput.setDeviceType(Integer.parseInt(deviceType));
		}
		
		String terminalType = request.getHeader(TERMINAL_TYPE);
		if(!StringUtils.isEmpty(terminalType)){
			reqHeaderInput.setTerminalType(Integer.parseInt(terminalType));
		}
		reqHeaderInput.setAccessToken(request.getHeader(ACCESS_TOKEN));
		reqHeaderInput.setSignature(request.getHeader(SIGNATURE));
		String timestamp = request.getHeader(TIMESTAMP);
		if(!StringUtils.isEmpty(timestamp)){
			reqHeaderInput.setTimestamp(Long.parseLong(timestamp));
		}
		String fromType = request.getHeader(FROM_TYPE);
		if(!StringUtils.isEmpty(fromType)){
			reqHeaderInput.setFromType(Integer.parseInt(fromType));
		}else{
			String origin = request.getHeader("origin");
			if(!StringUtils.isEmpty(origin) && isFromType(origin)){
				ctx.addZuulRequestHeader(FROM_TYPE, origin);
			}
		}
		ctx.set(HEADER,reqHeaderInput);
		return reqHeaderInput;
	}

	public <T> void handleResponse(RequestContext ctx,BaseOutput<T> output){
		HttpServletResponse response = ctx.getResponse();
        response.setCharacterEncoding("utf-8");  //设置字符集
        response.setContentType("application/json; charset=utf-8"); //设置相应格式
        response.setStatus(200);
        ctx.setResponse(response);
        try {
        	ctx.setSendZuulResponse(false); //不进行路由
        	String json = JSON.toJSONString(output);
            response.getWriter().write(json); //响应体
        } catch (IOException e) {
        	logger.error("zuul Filter处理response异常",e);
        }
	}
	
	public boolean isFromType(String origin){
		return !StringUtils.isEmpty(origin) && !origin.startsWith("http") && !origin.startsWith("https");
	}
}
